package springredis.com.lei.config;

import java.time.Duration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Created by Administrator on 2018/2/28.
 */
@Configuration
@EnableCaching //开启缓存
public class CacheConfig {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * redisTemplate配置
     * @return
     */
    @Bean
    public RedisTemplate redisTemplateInit() {
    	//json序列化
        Jackson2JsonRedisSerializer<Object> valueSerializer  =jackson2JsonRedisSerializer();
        //字符串序列化
        StringRedisSerializer keySerializer = new StringRedisSerializer();
        //string 序列化
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(valueSerializer);
        //hash序列化
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);
        return redisTemplate;
    }

    /**
     * 注解的默认配置
     * @return
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(){
        Jackson2JsonRedisSerializer<Object> fastJsonRedisSerializer =jackson2JsonRedisSerializer();
        RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig();
        
        configuration = configuration.serializeValuesWith
        		(RedisSerializationContext.SerializationPair.fromSerializer(fastJsonRedisSerializer))
        		.entryTtl(Duration.ofHours(30));
        //默认30小时
        return configuration;
    }

    public Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer() {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
                Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        return jackson2JsonRedisSerializer;
    }
}
